package cn.com.dhcc.turbo.service.registry;

import java.util.Iterator;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.dhcc.app.core.dao.CrudDao;
import cn.com.dhcc.app.core.exception.DaoException;
import cn.com.dhcc.app.core.exception.NiceException;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.AbstractCrudService;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.turbo.dao.registry.DataCategoryDao;
import cn.com.dhcc.turbo.dao.registry.DomainInfoDao;
import cn.com.dhcc.turbo.entity.registry.DataCategory;
import cn.com.dhcc.turbo.entity.registry.DomainInfo;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncOperType;
import cn.com.dhcc.turbo.entity.registry.SynchronizeInfo.SyncType;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.service.registry.sync.SynchronizeHandler;
/**
 * 数据分类Service
 * @日期：2014-9-29下午4:30:59
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
@Service
public class DataCategoryService extends AbstractCrudService<DataCategory> {
	@Autowired
	private DataCategoryDao dao;
	
	@Autowired
	private DomainInfoDao domainDao;
	@Autowired
	SynchronizeHandler synchronizeHandler;
	@Override
	public CrudDao<DataCategory> getCrudDao() {
		return dao;
	}
	private Logger log = Log.getLogger(LOGTYPE.TURBO);
	
	
	public PagerData<DataCategory> getPagerList(Pager pager,
			WhereCondition parameter) throws ServiceException{
		try {
			return dao.getPagerList(pager, parameter);
		} catch (Exception e) {
			log.error("获取数据分类列表异常"+e);
		}
		return null;
		
	}
	/**
	 * 修改并同步
	 * @param entity
	 * @throws ServiceException
	 * @throws NiceException
	 */
	public void updateDataCategoryAndSync(DataCategory entity) throws ServiceException, NiceException {
		super.updateIgnoreNull(entity);
		try {
			DataCategory inDBCategory = get(entity.getId());
			synchronizeHandler.syncToAllNodesFromLocalNode(SyncType.DATACATEGORY, false, inDBCategory, SyncOperType.UPDATE,true);
		} catch (Exception e) {
			throw new NiceException("添加成功，但数据同步失败，请手动同步!");
		}
	}
	/**
	 * 添加并同步
	 * @param entity
	 * @throws ServiceException
	 * @throws NiceException
	 */
	public void insertDataCategoryAndSync(DataCategory entity) throws ServiceException, NiceException {
		super.insert(entity);
		try {
			synchronizeHandler.syncToAllNodesFromLocalNode(SyncType.DATACATEGORY, false, entity, SyncOperType.INSERT,true);
		} catch (Exception e) {
			throw new NiceException("添加成功，但数据同步失败，请手动同步!");
		}
	}
	public String getRootDataCategoryTree(UserInfo userInfo) throws ServiceException{
		StringBuffer nodeTreeData = new StringBuffer();
		try {
//			NodeInfo localNode = nodeInfoDao.getLocalNode();
			nodeTreeData.append("[");
			nodeTreeData.append("{");
			nodeTreeData.append("id:'").append("#").append("',");
			nodeTreeData.append("pId:'").append("").append("',");
			nodeTreeData.append("name:'").append("数据分类").append("',");
			nodeTreeData.append("select:'").append("0").append("',");
			nodeTreeData.append("isAdd:'").append("0").append("',");
			nodeTreeData.append("isEdit:'").append("0").append("',");
			nodeTreeData.append("icon:'\'+_rs_image_path+\'/rsroot.png',");
			nodeTreeData.append("nocheck:").append(true).append(",");
			nodeTreeData.append("checked:").append(false).append(",");
			nodeTreeData.append("open:").append(true);
			nodeTreeData.append("}");
			List<DomainInfo> list = domainDao.getAll();
			for (Iterator<DomainInfo> iterator = list.iterator(); iterator.hasNext();) {
				DomainInfo vo = iterator.next();
				boolean checked = false;
				boolean isOpen = false;
				boolean isParent = false;
				nodeTreeData.append(",");
				nodeTreeData.append("{");
				nodeTreeData.append("id:'").append(vo.getId()).append("',");
				nodeTreeData.append("pId:'").append("#").append("',");
				nodeTreeData.append("name:'").append(vo.getName()).append("',");
				nodeTreeData.append("select:'").append("0").append("',");
				nodeTreeData.append("nocheck:").append(true).append(",");
				nodeTreeData.append("checked:").append(checked).append(",");
				nodeTreeData.append("open:").append(isOpen).append(",");
				nodeTreeData.append("isAdd:'").append("0").append("',");
				nodeTreeData.append("isEdit:").append("0").append(",");
				nodeTreeData.append("icon:'\'+_rs_image_path+\'/domain.png',");
				nodeTreeData.append("isParent:").append(isParent);
				nodeTreeData.append("}");
			}
		} catch (DaoException e) {
			throw new ServiceException("获取数据分类树失败", e);
		}
		nodeTreeData.append("]");
		return nodeTreeData.toString();
	}
	/**
	 * 获取子数据分类树
	 * @param pid
	 * @return
	 * @throws ServiceException
	 */
	public String dataCategoryTree(String pid,UserInfo userInfo) throws ServiceException {
		StringBuilder nodeTreeData = new StringBuilder();
		try {
//			NodeInfo localNode = nodeInfoDao.getLocalNode();
			List<DataCategory> list = dao.getListByPid(pid);
			nodeTreeData.append("[");
			for (Iterator<DataCategory> iterator = list.iterator(); iterator.hasNext();) {
				DataCategory vo = iterator.next();
				boolean isParent = false;
				nodeTreeData.append("{");
				nodeTreeData.append("id:'").append(vo.getId()).append("',");
				nodeTreeData.append("pId:'").append(vo.getPid()).append("',");
				nodeTreeData.append("name:'").append(vo.getDataName()).append("',");
				nodeTreeData.append("type:'").append(2).append("',");
				nodeTreeData.append("select:'").append("1").append("',");
				//nodeTreeData.append("sysId:'").append(vo.getSysId()).append("',");
				nodeTreeData.append("nocheck:").append(true).append(",");
				nodeTreeData.append("checked:").append(false).append(",");
				nodeTreeData.append("open:").append(false).append(",");
				if (!"".equals(vo.getCount()) && Integer.parseInt(vo.getCount()) > 0 ) {
					isParent = true;
				}
				
				nodeTreeData.append("icon:'\'+_rs_image_path+\'/dc.png',");
				nodeTreeData.append("count:'").append(vo.getCount()).append("',");
				nodeTreeData.append("isParent:").append(isParent);
				nodeTreeData.append("}");
				if (iterator.hasNext())
					nodeTreeData.append(",");
			}
			nodeTreeData.append("]");
		} catch (DaoException e) {
			throw new ServiceException("获取子数据分类树失败", e);
		}
		return nodeTreeData.toString();
	}
	
	
	/**
	 * 获取最大数据分类编码
	 * @param pid
	 * @return
	 * @throws ServiceException
	 *//*
	public String getMaxDataCodeByPid(String pid) throws ServiceException {
		try {
			return dao.getMaxDataCodeByPid(pid);
		} catch (DaoException e) {
			throw new ServiceException("获取最大数据分类编码失败", e);
		}
	}*/
	public String dataDomainCategoryTree(String domainId) throws ServiceException {
		StringBuilder nodeTreeData = new StringBuilder();
		try {
			List<DataCategory> list = dao.getListByDomainId(domainId);
			nodeTreeData.append("[");
			for (Iterator<DataCategory> iterator = list.iterator(); iterator.hasNext();) {
				DataCategory vo = iterator.next();
				boolean isParent = false;
				nodeTreeData.append("{");
				nodeTreeData.append("id:'").append(vo.getId()).append("',");
				nodeTreeData.append("pId:'").append(vo.getPid()).append("',");
				nodeTreeData.append("name:'").append(vo.getDataName()).append("',");
				nodeTreeData.append("type:'").append(2).append("',");
				nodeTreeData.append("select:'").append(true).append("',");
				nodeTreeData.append("domainId:'").append(domainId).append("',");
				nodeTreeData.append("nocheck:").append(true).append(",");
				nodeTreeData.append("checked:").append(false).append(",");
				nodeTreeData.append("open:").append(false).append(",");
				if (!"".equals(vo.getCount()) && Integer.parseInt(vo.getCount()) > 0 ) {
					isParent = true;
				}
				nodeTreeData.append("icon:'\'+_rs_image_path+\'/dc.png',");
				nodeTreeData.append("count:'").append(vo.getCount()).append("',");
				nodeTreeData.append("isParent:").append(isParent);
				nodeTreeData.append("}");
				if (iterator.hasNext())
					nodeTreeData.append(",");
			}
			nodeTreeData.append("]");
		} catch (DaoException e) {
			throw new ServiceException("获取子数据分类树失败", e);
		}
		return nodeTreeData.toString();
	}
	
	public int insertOrUpdateRemoteNode(DataCategory dataCategory)throws ServiceException {
		int r = super.insertOrUpdate(dataCategory);
		return r;
		
	}
	public boolean isPropertyUnique(String propertyName,String newValue,String oldValue)throws ServiceException {
		try {
			if (newValue.equals(oldValue)) {
				return true;
			}
			/*//List<SysInfo> list = sysDao.getLocalSysInfoList();
			String[] sys=new String[list.size()];
			for (int i = 0; i < list.size(); i++) {
				sys[i]=list.get(i).getId();
			}*/
			WhereCondition searchParameter = new WhereCondition();
			searchParameter.where().eq(propertyName, newValue);
			//searchParameter.and().in("sys_id", sys);
			return getCrudDao().count(searchParameter) == 0;
		} catch (DaoException e) {
			throw new ServiceException("获取数据分类信息失败", e);
		}
	}
	
	/**
	 * 判断数据分类是否加密
	 * @param dataCode
	 * @return
	 * @throws DaoException
	 */
	public boolean isEncode(String dataCode) throws ServiceException {
		try {
			return dao.isEncode(dataCode);
		} catch (DaoException e) {
			throw new ServiceException("获取数据分类是否加密失败", e);
		}
	}
	public String getMaxDataCodeByDomainId(String domainId) throws ServiceException {
		try {
			return dao.getMaxDataCodeByDomainId(domainId);
		} catch (DaoException e) {
			throw new ServiceException("获取数据分类是否加密失败", e);
		}
	}
	
	/**
	 * 获取适配器列表
	 * @param pager
	 * @param condition
	 * @return
	 * @throws DaoException
	 */
	public PagerData<DataCategory> getDataCategoryList(Pager pager,WhereCondition condition,String orgCode)  throws ServiceException {
		try {
			return dao.getDataCategoryList(pager, condition, orgCode);
		} catch (DaoException e) {
			throw new ServiceException("获取适配器列表失败", e);
		}
	}
	/**
	 * 取数据分类最大编码
	 * @param dcType
	 * @param orgCode
	 * @return
	 * @throws ServiceException
	 */
	public long localMaxCode(String dcType,String orgCode) throws ServiceException {
		try {
			return dao.localMaxCode(dcType,orgCode);
		} catch (DaoException e) {
			throw new ServiceException("获取数据分类编码失败", e);
		}
	};
}
